package com.tdcoding.chat.server;

import java.security.cert.CertificateException;

import javax.net.ssl.SSLException;

import com.tdcoding.chat.constants.ChatConstants;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class ChatServer {
	private EventLoopGroup bossGroup, workerGroup;

	public ChatServer() {
		try {
			initChatServer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void initChatServer() throws InterruptedException, CertificateException, SSLException {
		bossGroup = new NioEventLoopGroup(ChatConstants.SERVER_BOSS_THREADS);
		workerGroup = new NioEventLoopGroup(ChatConstants.SERVER_WORK_THREADS);
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_KEEPALIVE, true)
					.option(ChannelOption.TCP_NODELAY, true)
					.childHandler(new ChatInitializer());
			bootstrap.bind(ChatConstants.SERVER_CHAT_PORT).sync().channel()
					.closeFuture().sync();
		} finally {
			shutdownServer();
		}
		
	}

	/**
	 * 关闭服务器
	 */
	public void shutdownServer() {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
		try {
			bossGroup.terminationFuture().sync();
			workerGroup.terminationFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}  
	}
}